<template>
    <TCollapse title="物资审减订单">
        <div style="display: flex;align-items: center;color: #ff0000;line-height: 18px;margin-bottom: 10px;">
            根据&lt;供应链管理部&gt;要求只允许塔、房和电源等设备退至虚拟库（即退库类型允许选择可用不入库或不可用不入库），其余物资不允许退至虚拟库。
            <el-button class="pms-button-primary" @click="clickMaterialClassify">可退至虚拟库物料分类</el-button>
        </div>
        <Table id="myTable" :tableData="tableData" :columns="columns" :isSelection="false" @changeInput="changeInput"
            :workDetail="workDetail" :basicPrjDetail="basicPrjDetail" />
        <el-row :gutter="10" class="marginBottom14" type="flex" justify="center">
            <el-col :span="1.5">
                <el-button v-if="showBtn" class="pms-button-primary" style="margin-top: 20px;"
                    @click="saveInfo">保存明细</el-button>
                <el-button v-if="showMaterial" class="pms-button-primary" style="margin-top: 20px;"
                    @click="materialSend">物资退库</el-button>
            </el-col>
        </el-row>
        <el-dialog ref="materialClassification" v-dialogDrag :close-on-click-modal="false"
            :visible.sync="showMaterialClassification" width="70%">
            <div slot="title" class="dialog-header">可退至虚拟库物料分类</div>
            <material-classification v-if="showMaterialClassification" ref="cancelRetreatVisible" />
        </el-dialog>
    </TCollapse>
</template>

<script>
import Table from '@/views/declinebank/components/table.vue';
import { columns } from '../configOption'
import materialClassification from '@/views/material/components/materialClassification.vue'
import { getTableList, saveData, getTableCount, getDeclineId ,getSubmitCheck} from "@/api/declinebank/index"
import { handleSaveData } from "../components/handelEdit"
import { clonePage } from '@/utils'
export default {
    name: "ReviewReduceOrders",
    components: {
        Table,
        materialClassification
    },
    props: {
        prjDetail: {
            type: Object,
            default: () => ({})
        },
        workDetail: {
            type: Object,
            default: () => ({})
        },
        basicPrjDetail: {
            type: Object,
            default: () => ({})
        }
    },
    watch: {
        prjDetail: {
            handler(val) {
                if (JSON.stringify(val) !== '{}') {
                    // 获取表格信息
                    this.getTableInfo()
                }
            },
            deep: true,
            immediate: true
        },
    },
    computed: {
        showBtn() {
            return (this.$route.query.type === 'todo' && this.workDetail.activityDefID === 'reduce2_cs01') || this.$route.query.status === 'todo'
        },
        showMaterial() {
            return this.$route.query.type === 'todo' && this.workDetail.activityDefID === 'reduce2_cs05'
        },
    },
    data() {
        return {
            showMaterialClassification: false,
            tableData: [
            ],
            columns,
            precisionList: [] //精度
        }
    },
    methods: {
        arabicToChinese(num) {
            const chineseMap = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
            // 参数验证：确保是数字且在 0-9 范围内[6,7](@ref)
            if (typeof num !== 'number' || num < 0 || num > 9) {
                return '非数字或超出范围';
            }
            return chineseMap[num];
        },

        // 物资退库
        materialSend() {
            this.$emit('sendCancellStocks')
        },
        changeInputone(_spuUnitAcc, row, item, saveValue) {
            if (_spuUnitAcc === 0 && !(/^-?(0|[1-9]\d*)$/.test(row[item.prop])) && row[item.prop] !== ''&& !['keeperContact', 'keeper', 'keeperAddress'].includes(item.prop)) {
                row[item.prop] = (+row[item.prop]).toFixed(_spuUnitAcc)
            }
        },
        changeInputTwo(row, item, _spuUnitAcc) {
            if (!['keeperContact', 'keeper', 'keeperAddress'].includes(item.prop)) {
                row[item.prop] = (+row[item.prop]).toFixed(_spuUnitAcc)
            }
        },
        changeInput(row, item, saveValue) {
            // 当前行编辑的精度
            const precision = this.precisionList.find(items_ => items_.materialCode === row.pmsMaterialCode)
            const _spuUnitAcc = +precision?.spuUnitAcc //精度位数
            // 如果精度为0方法会失效
            const regex = new RegExp(`^-?(0|[1-9]\\d*)(\\.\\d{1,${_spuUnitAcc === 0 ? 1 : _spuUnitAcc}})?$`);
            this.changeInputone(_spuUnitAcc, row, item, saveValue)
            // 不允许输入01
            if (!regex.test(row[item.prop]) && row[item.prop] !== '' && _spuUnitAcc !== 0 && !['keeperContact', 'keeper', 'keeperAddress'].includes(item.prop)) {
                row[item.prop] = (+row[item.prop]).toFixed(_spuUnitAcc)
            }
            if (row[item.prop] === "" && !['keeperContact', 'keeper', 'keeperAddress'].includes(item.prop)) {
                row[item.prop] = 0
            }
            this.changeInputTwo(row, item, _spuUnitAcc)
            handleSaveData(row, item, saveValue, precision, this.basicPrjDetail.fieldProjectManager, this.basicPrjDetail.fieldProjectManagerName)
        },
        clickMaterialClassify() {
            this.showMaterialClassification = true;
        },
        async getTableInfo() {
            const params = { reduceId: this.workDetail?.bizObject?.bizSeq || this.$route.query.bizseq }
            const { code, data } = await getTableList(params)
            if (+code === 200) {
                this.tableData = data
                await this.getPrecisionList()
            }
        },
        // 获取精度
        async getPrecisionList() {
            const params = {
                materialCodes: this.tableData.map(item => item.pmsMaterialCode).join(',')
            }
            const { code, data } = await getTableCount(params)
            if (+code === 200) {
                this.precisionList = data
            }
        },
        // 获取workItemID
        async getDeclineIdInfo(params) {
            if (this.$route.query.status === 'todo') {
                await this.checkSaveInfo()
                const { code, data } = await getDeclineId(params)
                if (+code === 200) {
                    window.open(`${process.env.VUE_APP_ZHONGRUAN_URL}handleDeclineBank?workItemId=${data.workItemId}&type=todo`, '_blank')
                    clonePage()
                }
            }
        },
        async checkSaveInfo(){
            // 后端校验
            const { code } = await getSubmitCheck({ reduceId: this.$route.query.bizseq  })
            if (+code !== 200) {
                return Promise.reject()
            }
        },
        async statueSave() {
            if (!this.basicPrjDetail.isNormalLoss && this.$route.query.status === 'todo') {
                this.$message.warning('请选择该项目是否为正常损耗！')
                throw ""
            }
        },
        // 一码到底校验
        async checkYYMD() {
            for (let i = 0; i < this.tableData.length; i++) {
                let data2 = this.tableData[i];
                // let spu_unit_acc = this.precisionList.find(item => item.materialCode === data2.pmsMaterialCode).spuUnitAcc;
                let spu_main_code = this.precisionList.find(item => item.materialCode === data2.pmsMaterialCode).spuMainCode;
                if (spu_main_code === "1") {
                    this.$message.error("物料" + data2.pmsMaterialCode + "为主设备物资，不允许调减，请联系管理员!");
                    throw ""
                }
            }
        },
        async checkAmount() {
            let reduceAmount = 0;
            for (let i = 0; i < this.tableData.length; i++) {
                let nums = this.tableData[i];
                reduceAmount = reduceAmount + nums.noMaterialReduceAmount;
            }
            if (reduceAmount >= 500 && this.basicPrjDetail.isNormalLoss === "0") {
                this.$message.warning("无实物审减金额之和大于500元，该项目只能为非正常损耗，请修改！");
                throw "";
            }
        },
        // 保存数据
        async saveInfo(type) {
            await this.statueSave();
            const params = {
                id: this.workDetail?.bizObject?.bizSeq || this.$route.query.bizseq,
                prjId: this.prjDetail.prjId,
                isNormalLoss: this.basicPrjDetail.isNormalLoss,
                auditDeclineItemVoList: this.tableData,
            }
            const { code } = await saveData(params)
            if (+code !== 200) {
                throw "";
            }
            if (type&& this.$route.query.status !== 'todo') {
                this.$message.success('保存成功')
            }
            await this.getTableInfo()
            await this.getDeclineIdInfo(params)
        },
    },
}

</script>
<style lang="scss" scoped>
::v-deep .el-table thead.is-group th.el-table__cell {
    background: none;
}
</style>